package mspbots.autotask.data.core.clientportalusers;

import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import mspbots.autotask.common.ResultMsg;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.time.Duration;

@Log4j2
@Component
@RequiredArgsConstructor
public class ClientPortalUsersReceiver {

    private final ClientPortalUsersRespository clientPortalUsersRespository;

    @RabbitListener(queues = "auto-task.client-portal-users.sync")
    public void syncTask(ResultMsg content) {

        ClientPortalUser clientPortalUser = ClientPortalUser.builder().otherId(content.getId())
                .tenantId(content.getTenantId())
                .syncTime(content.getSyncDate())
                .entity(content.getEntity())
                .build();

        if (ObjectUtils.isEmpty(clientPortalUser.getOtherId())) {
            return;
        }

        this.clientPortalUsersRespository.findByOtherIdAndTenantId(content.getId(), content.getTenantId())
                .map(oldServiceCallTicketResources -> {
                    clientPortalUser.setId(oldServiceCallTicketResources.getId());
                    return clientPortalUser;
                })
                .defaultIfEmpty(clientPortalUser)
                .flatMap(this.clientPortalUsersRespository::save)
                .block(Duration.ofSeconds(10));


    }
}
